package fr.afcepf.iziticket.dao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import fr.afcepf.iziticket.dao.interfaces.DAOSpectacle;
import fr.afcepf.iziticket.entities.Seance;
import fr.afcepf.iziticket.entities.Spectacle;
import fr.afcepf.iziticket.entities.SpectacleDonnees;

@Transactional
public class DAOSpectacleImpl extends ObjectDaoImpl<Spectacle> implements DAOSpectacle{

	public DAOSpectacleImpl()
	{
		this.setTableName("Spectacle");
	}
	
	@Override
	public Spectacle get(int paramId) {
		return (Spectacle) this.hibernateTemplate.get(Spectacle.class, paramId);
	}


	public void addSeanceToSpectacle(int idSeance, int idSpectacle) {
		Spectacle spectacle = (Spectacle) hibernateTemplate.get(Spectacle.class, idSpectacle);
		Seance seance = (Seance) hibernateTemplate.get(Seance.class, idSeance);
		spectacle.getSeances().add(seance);
		seance.setSpectacle(spectacle);
	}


	public void addSpectacleDonneesToSpectacle(int idSpectacleDonnee,
			int idSpectacle) {
		Spectacle spectacle = (Spectacle) hibernateTemplate.get(Spectacle.class, idSpectacle);
		SpectacleDonnees spectacleDonnee = (SpectacleDonnees) hibernateTemplate.get(SpectacleDonnees.class, idSpectacleDonnee);
		spectacle.setSpectacleDonnees(spectacleDonnee);
		spectacleDonnee.getSpectacles().add(spectacle);
		
	}
	

	public List<Spectacle> rechercheSpectacles(String nom, String lieu, int prixMin, int prixMax, int idGenre, int idAudience, int nbJourDateAdd){
		String sReqWhere = "";

		if (idGenre > 0) {
			sReqWhere = " and s.spectacleDonnees.genre.idGenre = " +idGenre;
		}
		if (idAudience > 0) {
			sReqWhere += " and s.spectacleDonnees.audience.idaudience = "+idAudience;
		}
		Date dateNow = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(dateNow);
		cal.add(Calendar.DATE, nbJourDateAdd);
		java.sql.Date dateSql = new java.sql.Date(cal.getTimeInMillis());
		String dateDeb = dateSql.toString() + " 00:00:00";
		
		if (nbJourDateAdd > -1) {
			String dateFin = dateSql.toString() + " 23:59:59";
			sReqWhere += " AND a.dateSeance <= '"+dateFin+"'";
			
			System.out.println("dateDeb = "+dateDeb);	
		}else{
			
		}

		String query = "SELECT DISTINCT s FROM Spectacle s, Seance a "
				+ " WHERE a in elements(s.seances) AND a.dateSeance >= '"+dateDeb+"' AND a.placesVendues < s.nombrePlaces"
				+ " AND s.spectacleDonnees.nom LIKE '%"+nom+"%'"
				+ " AND (s.theatre.adresse.ville LIKE '%"+lieu+"%'"
				+ " OR s.theatre.adresse.codePostal LIKE '"+lieu+"%')"
				+ " AND s.puht * (1 + s.tva.valeurTva)>="+prixMin+" AND s.puht * (1 + s.tva.valeurTva)<="+prixMax
				+ sReqWhere;
		
		@SuppressWarnings("unchecked")
		List<Spectacle> list = (List<Spectacle>) hibernateTemplate.find(query);

		return list;
	}
	
	
}
